import React, { useState, useRef } from "react";
import Tesseract from "tesseract.js";

const Camera = () => {
  // 初始化状态
  const [image, setImage] = useState<any>(null);
  const [result, setResult] = useState<any>("");
  const [loading, setLoading] = useState<any>(false);

  // 创建 ref 引用
  const videoRef = useRef<any>(null);
  const canvasRef = useRef<any>(null);

  // 摄像头启动
  const startCamera = () => {
    navigator.mediaDevices
      .getUserMedia({ video: true })
      .then((stream) => {
        videoRef.current.srcObject = stream;
        videoRef.current.play();
      })
      .catch((error) => {
        console.log("Error starting camera: ", error);
      });
  };

  // 拍照
  const takePicture = () => {
    setLoading(true);
    // 将视频帧绘制到画布上
    const context = canvasRef.current.getContext("2d");
    context.drawImage(
      videoRef.current,
      0,
      0,
      canvasRef.current.width,
      canvasRef.current.height
    );

    // 将画布转换为图像 URL
    const dataURL = canvasRef.current.toDataURL("image/jpeg");

    // 设置图像 URL
    setImage(dataURL);

    // 使用 Tesseract.js 识别身份证号
    Tesseract.recognize(dataURL, "chi_sim", { logger: (m) => console.log(m) })
      .then((result) => {
        setResult(result.data.text.replace(/\s+/g, ""));
        setLoading(false);
      })
      .catch((error) => {
        console.log("Error recognizing text: ", error);
        setLoading(false);
      });
  };

  return (
    <div>
      <h1>拍照识别身份证号</h1>
      <div>
        <button onClick={startCamera}>启动摄像头</button>
        <button onClick={takePicture}>拍照识别</button>
      </div>
      <div>
        {/* 显示视频 */}
        <video
          ref={videoRef}
          style={{ display: "none" }}
          width="640"
          height="480"
        />
        {/* 显示图像 */}
        {image && <img src={image} width="640" height="480" />}
        {/* 显示识别结果 */}
        {result && <h2>身份证号：{result}</h2>}
        {/* 显示加载状态 */}
        {loading && <h2>识别中...</h2>}
        {/* 显示画布 */}
        <canvas
          ref={canvasRef}
          style={{ display: "none" }}
          width="640"
          height="480"
        />
      </div>
    </div>
  );
};

export default Camera;